package pers.sports.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import pers.sports.entity.Notice;
import pers.sports.service.NoticeService;
import pers.sports.vo.NoticeInfo;
import pers.sports.vo.StorageUser;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 公告处理
 *
 * @datetime 2021/3/30 14:35
 */

@Controller
@RequestMapping("/notice")
public class NoticeController {

    private final NoticeService noticeService;


    @Autowired
    public NoticeController(NoticeService noticeService) {
        this.noticeService = noticeService;
    }

    @ResponseBody
    @RequestMapping("/findAllNoticeInfo")
    public Map<String, Object> findAllNoticeInfo(Integer page, Integer limit) {
        Map<String, Object> map = new HashMap<>();
        List<NoticeInfo> list = noticeService.findAllNoticeInfo(page, limit);
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", noticeService.countNumber());
        map.put("data", list);
        return map;
    }

    @RequestMapping(value = "/findNoticeById", method = RequestMethod.GET)
    public ModelAndView findNoticeById(String noticeId) {
        Notice notice = noticeService.findNoticeById(noticeId);
        ModelAndView mv = new ModelAndView("notice");
        mv.addObject(notice);
        return mv;
    }

    @ResponseBody
    @RequestMapping(value = "/newNotice", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public String newNotice(@RequestBody JSONObject jsonObject) {
        Notice notice = new Notice();
        notice.setNoticeTitle(jsonObject.get("title").toString());
        notice.setNoticeDate(jsonObject.get("time").toString());
        notice.setNoticeContent(jsonObject.get("detail").toString());
        notice.setNoticeAuthor(jsonObject.get("author").toString());
        if (noticeService.insertNotice(notice)) {
            return "success";
        } else {
            return "fail";
        }
    }

    @ResponseBody
    @RequestMapping("delete")
    public String deleteNotice(@RequestParam("id[]") String[] id, HttpServletRequest req){
        for (int i = 0; i < id.length; i++) {
            noticeService.deleteNoticeById(id[i]);
        }
        return "success";
    }
}
